package com.weibo.click.local;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj.barcode.ConstantStri;
import com.bj.barcode.RobotPos;

public class WeiboUtils {
	   private static final String token=";";

	   public static List<String> trueMessages=new ArrayList<String>();
	   public static List<String> keywordsWeibo=new ArrayList<String>();
	   public static List<String> truthURLs=new ArrayList<String>();
	   private static final Log logger = LogFactory.getLog(WeiboUtils.class);
		//Weibo - 可用，未分配给客户端的微博账号
		private final static ConcurrentLinkedQueue<QQWeiBo> weiboFreeUsers=new ConcurrentLinkedQueue<QQWeiBo>();
		//Weibo - 全部微博账号
		public final static ConcurrentHashMap<String,QQWeiBo> allWeiboUsers=new ConcurrentHashMap<String,QQWeiBo>();
		private final static Lock lck=new ReentrantLock();
	   
	   //优先执行的部分
	   static{
		   parseSingleConf(ConstantStri.messages,trueMessages); 
		   parseSingleConf(ConstantStri.keywords,keywordsWeibo); 
		   parseSingleConf(ConstantStri.urls,truthURLs); 
		   loadWeiboUsrsFromFiles(ConstantStri.weiboUsersFile);//微博用户名密码配置文件
	   }
	   public static RobotPos[] parseConf()
		{
			RobotPos[] pos=new RobotPos[1000];
	    	InputStreamReader rd = null;
	    	BufferedReader in= null;
	    	
	    	try {
				 
				File conf = new File(ConstantStri.barCodeConf); 
				String s =""; 
				String xPos="0",yPos="0",width="0",len="0",action="";
				rd =new InputStreamReader(new FileInputStream(conf), "UTF-8");
				in = new BufferedReader(rd);
				int i=0;
				while( (s = in.readLine()) != null) {
					RobotPos rob=new RobotPos();
					if(s.trim().length()<=1){
						break;
					}
					StringTokenizer fenxi=new StringTokenizer(s,ConstantStri.token); //空格和逗号做分
					try {
						xPos=fenxi.nextToken().trim();
					} catch (NoSuchElementException e) {
						xPos="0";
						break;
					}
					try {
						yPos=fenxi.nextToken().trim();
					} catch (NoSuchElementException e) {
						yPos="0";
						break;
					}
					try {
						width=fenxi.nextToken().trim();
					} catch (NoSuchElementException e) {
						width="0";
						break;
					}
					try {
						len=fenxi.nextToken().trim();
					} catch (NoSuchElementException e) {
						len="0";
						break;
					}
					try {
						action=fenxi.nextToken();//解析占用标志
					} catch (NoSuchElementException e) {
						break;
					}
					rob.setAction(action);
					rob.setxPos(Integer.parseInt(xPos));
					rob.setyPos(Integer.parseInt(yPos));
					rob.setWidth(Integer.parseInt(width));
					rob.setLength(Integer.parseInt(len));
					logger.info("开始加载保存的weibo链接......");
					if(action==null || action.trim().equals("")
						|| xPos==null || xPos.trim().equals("")){
						break;
					}
					pos[i]=rob;
					i++;
				}//while
			}  catch (FileNotFoundException e) {
				logger.info(e);
			} catch (IOException e) {
				logger.info(e);
			}finally{
				try {
					rd.close();
					in.close();
				} catch (IOException e) {
					logger.info(e);
				}
			}
	    	return pos;
	}
	public static void parseSingleConf(String file,List result){
	    	InputStreamReader rd = null;
	    	BufferedReader in= null;
	    	
	    	try {
				File conf = new File(file); 
				String s =""; 
				rd = 
					new InputStreamReader(new FileInputStream(conf), "UTF-8");
				in = new BufferedReader(rd);
				while( (s = in.readLine()) != null) {
					result.add(s);
				}//while
			}  catch (FileNotFoundException e) {
				logger.info(e);
			} catch (IOException e) {
				logger.info(e);
			}finally{
				try {
					rd.close();
					in.close();
				} catch (IOException e) {
					logger.info(e);
				}
			}
	}
    /*从文件load微薄用户的信息*/
    public static void loadWeiboUsrsFromFiles(String confPath){
    	InputStreamReader rd = null;
    	BufferedReader in= null;
    	
    	try {
			
			
			FilenameFilter filter = new FilenameFilter() { 
			    public boolean accept(File dir, String name) { 
			        return name.endsWith("weiboUsr.txt"); 
			    } 
			}; 
			 
			File folder = new File(confPath); 
			File[] listOfFiles = folder.listFiles(filter); 
			String s =""; 
			String usr="",pass="",group="",usedFlag="";
			int msgCount=0;

			rd = 
				new InputStreamReader(new FileInputStream(listOfFiles[0]), "UTF-8");
			in = new BufferedReader(rd);
			while( (s = in.readLine()) != null) {
				if(s.trim().length()<=1){
					break;
				}
				StringTokenizer fenxi=new StringTokenizer(s,token); //空格和逗号做分
				try {
					usr=fenxi.nextToken().trim();//解析用户名
				} catch (NoSuchElementException e) {
					continue;
				}
				try {
					pass=fenxi.nextToken().trim();//解析密码
				} catch (NoSuchElementException e) {
					continue;
				}
				try {
					group=fenxi.nextToken().trim();//解析组别
				} catch (NoSuchElementException e) {
					continue;
				}
				try {
					String count=fenxi.nextToken().trim();//累计发送的消息数量
					if(count==null || count.trim().equals("") || count.trim().length()==0){
						msgCount=0;
					}else{
						msgCount=Integer.parseInt(count)
;					}
				} catch (NoSuchElementException e) {
					msgCount=0;
				} catch (NumberFormatException e) {
					msgCount=0;
					//logger.info(e);
				} 
				try {
					usedFlag=fenxi.nextToken().trim();//用户 分配标志
				} catch (NoSuchElementException e) {
					usedFlag="N";
				}
				//logger.info("开始加载weibo用户名和密码...");
				if(usr==null || usr.trim().equals("")
						|| pass==null || pass.trim().equals("")){
					return;
				}else{
					QQWeiBo weibo=new QQWeiBo();
					weibo.setGroup(group);
					weibo.setUser(usr);
					weibo.setPass(pass);
					weibo.setMsgCount(msgCount);
					weibo.setUsedFlag(usedFlag);
					addWeiboUser(weibo);
					//logger.info("usr=="+usr+"  pass=="+pass+"  group=="+group+"  msgCount=="+msgCount+"  usedFlag=="+usedFlag);
				}
			}//while
		} catch (FileNotFoundException e) {
			//logger.info(e);
		} catch (IOException e) {
			//logger.info(e);
		}finally{
			try {
				rd.close();
				in.close();
			} catch (IOException e) {
				//logger.info(e);
			}
		}
    	return;
    }
	/*把一个微薄用户分配给客户端*/
	public static QQWeiBo allocWeiboUser(){
		try {
			QQWeiBo weibo=weiboFreeUsers.poll();
			weibo.setUsedFlag("N");
			logger.info("weibo用户"+weibo.getUser()+" 分配了！");
			if(weibo==null){
				logger.info("没有可用的微薄用户了!");
				return null;
			}else{
				weiboFreeUsers.add(weibo);
				logger.info("weibo用户"+weibo.getUser()+" 将被添加到分配的用户队列的尾部");
				return weibo;		
			}
		}catch(Exception e){
		    logger.error(e);
		    return null;
		}
	}
	
	/*回收一个微薄用户*/
	
	public boolean freeWeiboUser(String username,String group){
		
		boolean flag=true;
		if(username==null || username.equals("")){
	    	logger.info("username= null, no user released!");
			return true;
		}
		lck.lock();
	    try {
	    	logger.info("username="+username);
	    	QQWeiBo usr=allWeiboUsers.get(username);
	    	if(usr!=null){
	    		usr.setUsedFlag("N");
	    		allWeiboUsers.put(username, usr);
	    	}

	    }catch(Exception e){
		    logger.error(e);
		    flag=false;
		}
	    finally {
			 lck.unlock();
		}
		
		return flag;
	}
	/*增加/刷新一个微薄用户的登陆信息*/
	public static boolean addWeiboUser(QQWeiBo usr){
		boolean flag=true;
		lck.lock();
	     try {
	    	usr.setUsedFlag("N");
	 		allWeiboUsers.put(usr.getUser(), usr);// 增加一个微薄用户账号
	 		weiboFreeUsers.add(usr);              //同时增加一个可用的微薄用户账号
			logger.info("新增加微薄用户了!"+usr.getUser()+usr.getPass());
	     }catch(Exception e){
		    logger.error(usr);
	    	logger.error(e);
	    	flag=false;
	     }
	     finally {
	    	 lck.unlock();
	     }
	     return flag;
	}
	//生成一条真相的消息
    public static String getTruthMsg(){
        int idx=0;
        idx=(int) (System.currentTimeMillis() % trueMessages.size());
        String msg=trueMessages.get(idx);
        idx=0;
        idx=(int) (System.currentTimeMillis() % truthURLs.size());
        String url=truthURLs.get(idx);
        idx=0;
        idx=(int) (System.currentTimeMillis() % keywordsWeibo.size());
        String keyword=keywordsWeibo.get(idx);
        msg.replaceAll("#url#", url);//文件中需要用#url#代替
        msg.replaceAll("#key#", keyword);
        
        return null;
    }
}
